package com.example.happytime;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

public class JokeFragment extends BaseFragment {
    PullToRefreshListView jokeLv;
    List<String> data;
    ArrayAdapter<String> adapter;
    int page = 1;
    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_joke, container, false);
        jokeLv = view.findViewById(R.id.joke_lv);
        data = new ArrayList<>();
        adapter = new ArrayAdapter<>(getContext(), R.layout.item_joke, R.id.item_joke_tv, data);
        jokeLv.setAdapter(adapter);
        String url = getJokeUrl(page);
        connectNetwork(url);
        setRefresh();
        return view;
    }
    //设置上拉加载（分页），下拉刷新
    private void setRefresh() {
        jokeLv.setMode(PullToRefreshBase.Mode.BOTH);
        jokeLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                jokeLv.onRefreshComplete();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                String jokeUrl = getJokeUrl(page);//获取下一页的网址
                connectNetwork(jokeUrl);//下一页的联网请求
            }
        });
    }

    private String getJokeUrl(int page) {
        String key = "680ca9398eb1a6304d1ab411b66e58a1";
        String url = "http://v.juhe.cn/joke/content/list.php?key="+key+"&page="+page+"&pagesize=10&sort=asc&time=1418745237";
        return url;
    }
    @Override
    public void onSuccess(String result) {
        JokeBean jokeBean = new Gson().fromJson(result, JokeBean.class);
        List<JokeBean.ResultBean.DataBean> list = jokeBean.getResult().getData();
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i).getContent();
            data.add(s);
        }
        adapter.notifyDataSetChanged();
        jokeLv.onRefreshComplete();
    }
}
